//
//  GNRAlertView.m
//  app
//
//  Created by LvYuan on 16/8/18.
//  Copyright © 2016年 UU. All rights reserved.
//

#import "GNRAlertView.h"
#import "GNRAlertConfiguration.h"

@interface GNRAlertView ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, assign) BOOL isShown;//是否已经show
@property (nonatomic, assign) BOOL isTimerAlert;//是否 定时提示框
@property (nonatomic, assign) BOOL isVertical;//按钮是否纵向排列
@property (nonatomic, assign) NSInteger totalBtnCount;//按钮总数

@property (nonatomic, assign) GNRAlertFieldStyle alertFieldStyle;//弹窗输入框类型

@property (nonatomic, strong) UIWindow    * containerWindow;//容器Window

@property (nonatomic, strong) UIButton    * maskView;//透明黑色遮罩
@property (nonatomic, strong) UIView      * alertView;//提示框矩形视图
@property (nonatomic, strong) UIImageView * headerView;//带有icon的头部
@property (nonatomic, strong) UIImageView * iconImgView;//icon
@property (nonatomic, strong) UIView      * contentView;//放标题等的父视图
@property (nonatomic, strong) UITableView * tableView;//多个按钮采用tableView
@property (nonatomic, strong) UILabel     * titleLabel;//标题
@property (nonatomic, strong) UILabel     * msgLabel;//内容
@property (nonatomic, strong) UIButton    * linkBtn;//链接按钮
@property (nonatomic, strong) UIButton    * cancelBtn;//取消按钮

@property (nonatomic, strong) NSMutableArray *textFields;//输入框数组
@property (nonatomic, strong) NSMutableArray <NSString *> *otherBtnTips;//其他按钮文字数组
@property (nonatomic, strong) NSMutableArray <UIButton *> *otherBtns;//所有按钮存放的数组
@property (nonatomic, strong) NSMutableArray <NSString *> *totalBtnTips;//所有文字数组,用于大于3个按钮的选择框

@property (nonatomic, strong) NSTimer * timer;//定时器
@property (nonatomic, strong) GNRAlertConfiguration * configuration;//弹窗UI配置

@property (nonatomic, copy) NSString * linkTip;//链接按钮文字


/**2018.5.3新增*/
@property (nonatomic,strong)UIImageView *waringImage;//警报
@property (nonatomic,strong)UILabel *titleLab;//标题文字
@property (nonatomic,strong)UILabel *desLab;//描述性文字
@property (nonatomic,strong)UIButton *knowBtn;//操作按钮
@property (nonatomic,strong)UIWindow *coverWindow;
@property (nonatomic,strong)UIButton *sureBtn;//多个的时候
@property (nonatomic,strong)UITextView *quickPhrasesTF;//常用语输入框
@property (nonatomic,strong)UILabel *placeLab;//占位符label
@property (nonatomic,strong)UITextField *moneyTextFiled;//占位符label
@property (nonatomic,copy)  NSString *desStr;
@property (nonatomic,strong)UITextView *versionUpdateTV;
@property (nonatomic,strong)UIButton *dismissBtnClcik;
@property (nonatomic,assign)BOOL isShow;


- (instancetype)initWithTitle:(NSString *)title msg:(NSString *)msg cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips actionCallback:(GNRAlertViewActionBlock)callback;

@end

@implementation GNRAlertView
{
    NSUInteger _countDownMaxTime;
    NSString * tmpText;//输入前的文字
    NSInteger actionSenderTag;
    BOOL alertBtnActionDismissBlockEnable;
    BOOL linkBtnActionDismissBlockEnable;
}

//MARK: - Deinit
- (void)dealloc{
    [self freeTimer];
    [self removeNotifications];
    GNRAlertLog(@"GNRAlertView dealloc");
}

//销毁timer
- (void)freeTimer{
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - Getter
- (UIWindow *)containerWindow{
    if (!_containerWindow) {
        _containerWindow = [[UIWindow alloc]initWithFrame:GNR_SCREENBOUNDS];
        _containerWindow.windowLevel = UIWindowLevelAlert;
        _containerWindow.hidden = NO;
        [_containerWindow makeKeyAndVisible];
    }
    return _containerWindow;
}

- (UIButton *)maskView{
    if (!_maskView) {
        _maskView = [UIButton buttonWithType:UIButtonTypeSystem];
        _maskView.backgroundColor = [UIColor clearColor];
        _maskView.frame = self.bounds;
        [_maskView addTarget:self action:@selector(maskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _maskView;
}

- (UIView *)alertView{
    if (!_alertView) {
        _alertView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.configuration.kAlertWidth, self.configuration.kAlertHeight)];
        _alertView.layer.masksToBounds = true;
        _alertView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        _alertView.clipsToBounds = true;
        _alertView.layer.cornerRadius = 8;
        [self addSubview:_alertView];
    }
    return _alertView;
}

- (UIImageView *)headerView{
    if (!_headerView) {
        _headerView = [[UIImageView alloc]initWithFrame:CGRectZero];
        [self.alertView addSubview:_headerView];
        _headerView.backgroundColor = [UIColor whiteColor];
        _headerView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _headerView;
}

- (UIImageView *)iconImgView{
    if (!_iconImgView) {
        _iconImgView = [[UIImageView alloc]initWithImage:[GNRAlertManager manager].defaultIconImage];
        [self.alertView addSubview:_iconImgView];
    }
    return _iconImgView;
}

- (UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, self.headerView.frame.size.height, self.configuration.kAlertWidth, 0)];
        _contentView.backgroundColor = [UIColor clearColor];
        [self.alertView addSubview:_contentView];
    }
    return _contentView;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:self.configuration.kTitFontSize];
        _titleLabel.numberOfLines = 0;
        _titleLabel.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)msgLabel{
    if (!_msgLabel) {
        _msgLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.configuration.kLeadPadding, 0, 0, 0)];
        _msgLabel.textAlignment = self.msgLabelAlignment;
        _msgLabel.font = [UIFont systemFontOfSize:self.configuration.kMsgFontSize];
        _msgLabel.numberOfLines = 0;
        _msgLabel.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_msgLabel];
    }
    return _msgLabel;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.configuration.kAlertWidth, 0) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = self.configuration.kBtnHeight;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.alertView addSubview:_tableView];
    }
    return _tableView;
}

- (GNRAlertConfiguration *)configuration{
    if (!_configuration ) {
        _configuration = [GNRAlertConfiguration new];
    }
    return _configuration;
}

- (NSUInteger)countDownMaxTime{
    if (!_countDownMaxTime) {
        _countDownMaxTime = [GNRAlertConfiguration kDefaultCountDownMaxTime];
    }
    return _countDownMaxTime;
}

#pragma mark - New View
- (UITextField *)newTextField{
    UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 0, self.configuration.kBtnHeight)];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.layer.masksToBounds = true;
    textField.layer.cornerRadius = 4;
    textField.borderStyle = UITextBorderStyleNone;
    textField.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    textField.layer.borderWidth = 1;
    textField.delegate = self;
    [self.contentView addSubview:textField];
    //注册监听
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventAllEditingEvents];
    return textField;
}

- (GNRTextView *)newTextView{
    GNRTextView * textView = [[GNRTextView alloc]initWithFrame:CGRectMake(0, 0, 0, self.configuration.kBtnHeight * 2)];
    textView.layer.masksToBounds = true;
    textView.layer.cornerRadius = 4;
    textView.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    textView.layer.borderWidth = 1;
    [self.contentView addSubview:textView];
    return textView;
}

- (NSMutableArray *)textFields{
    if (!_textFields) {
        _textFields = [NSMutableArray array];
    }
    return _textFields;
}

- (UIButton *)newBtn{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(alertBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] size:CGSizeMake(2, 2)] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor groupTableViewBackgroundColor] size:CGSizeMake(2, 2)] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    return btn;
}

- (UIButton *)newLinkBtn{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn addTarget:self action:@selector(linkBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_linkTip];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [btn setAttributedTitle:str forState:UIControlStateNormal];
    return btn;
}

//Money left icon
- (UIView *)newMoneyIconView{
    UIView * iconView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.configuration.kBtnHeight, self.configuration.kBtnHeight)];
    UILabel * icon = [[UILabel alloc]initWithFrame:iconView.bounds];
    icon.textColor = GNRGrayTextColor;
    icon.textAlignment = NSTextAlignmentCenter;
    icon.text = @"￥";
    [iconView addSubview:icon];
    return iconView;
}


#pragma mark - Setter
- (void)setTitle:(NSString *)title{
    _title = title;
    [self updateTitleMsgHeaderView];
    [self layoutAllSubviews];
}

- (void)setMsg:(NSString *)msg{
    _msg = msg;
    [self updateTitleMsgHeaderView];
    [self layoutAllSubviews];
}

- (void)setCancelBtnTip:(NSString *)cancelBtnTip{
    _cancelBtnTip = cancelBtnTip;
    [self installButtons];
    [self layoutBtns];
}

- (void)setAlertStyle:(GNRAlertStyle)alertStyle{
    _alertStyle = alertStyle;
}

- (void)setOtherBtnTips:(NSMutableArray<NSString *> *)otherBtnTips{
    _otherBtnTips = otherBtnTips;
}

- (void)setUpLimitMoney:(double)upLimitMoney{
    _upLimitMoney = upLimitMoney;
    NSAssert(_upLimitMoney>1.f&&_upLimitMoney<[GNRAlertConfiguration kMaxUpLimitMoney], @"金额上限,必须大于1.0,小于100,000,000.0");
}

- (void)setcountDownMaxTime:(NSUInteger)countDownMaxTime{
    _countDownMaxTime = countDownMaxTime;
    NSAssert((int)_countDownMaxTime>0, @"countDownMaxTime 必须大于0");
}

- (void)setIsTimerAlert:(BOOL)isTimerAlert{
    _isTimerAlert = isTimerAlert;
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    }
    [self stopTimer];
}

#pragma mark - Initial
- (instancetype)init{
    if (self = [super initWithFrame:GNR_SCREENBOUNDS]) {}
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)title msg:(NSString *)msg cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips actionCallback:(GNRAlertViewActionBlock)callback{
    if (self = [super init]) {
        self.title = title;
        self.msg = msg;
        self.otherBtnTips = [NSMutableArray arrayWithArray:otherBtnTips];
        self.cancelBtnTip = cancelBtnTip;
        _actionBlock = nil;
        _actionBlock = [callback copy];
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)title alertFieldStyle:(GNRAlertFieldStyle)alertFieldStyle cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips textFieldActionCallback:(GNRAlertViewTextFieldActionBlock)callback{
    if (self = [super init]) {
        self.title = title;
        self.otherBtnTips = [NSMutableArray arrayWithArray:otherBtnTips];
        self.cancelBtnTip = cancelBtnTip;
        _fieldAlertBlock = nil;
        _fieldAlertBlock = [callback copy];
        _alertFieldStyle = alertFieldStyle;
    }
    return self;
}

//快捷提示
+ (void)alertWithTitle:(NSString *)title msg:(NSString *)msg{
    [[GNRAlertView alertWithTitle:title msg:msg cancelBtnTip:nil otherBtnTips:@[@"确定"] actionCallback:nil] show];
}

//类方法带有链接形式的提示框
+ (instancetype)alertWithTitle:(NSString *)title linkTip:(NSString *)linkTip cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips actionCallback:(GNRAlertViewActionBlock)callback linkActionBlock:(GNRLinkActionBlock)linkBlock{
    GNRAlertView * alert = [[self alloc]initWithTitle:title msg:nil cancelBtnTip:cancelBtnTip otherBtnTips:otherBtnTips actionCallback:[callback copy]];
    alert.linkTip = linkTip;
    alert.linkActionBlock = [linkBlock copy];
    alert.alertStyle = GNRAlertStyleBig;
    return alert;
}

/**
 *  自定义内容提示框
 */
+ (instancetype)alertWithTitle:(NSString *)title customView:(UIView *)customView cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips actionCallback:(GNRAlertViewActionBlock)callback{
    GNRAlertView * alert = [[self alloc]initWithTitle:title msg:nil cancelBtnTip:cancelBtnTip otherBtnTips:otherBtnTips actionCallback:[callback copy]];
    alert.alertStyle = GNRAlertStyleNoHeader;
    alert.alertFieldStyle = GNRAlertFieldStyleCustomView;
    alert.customView = customView;
    alert.cancelBtnAlignment = GNRAlertCancelBtnAlignmentRight;
    return alert;
}

//类方法
+ (instancetype)alertWithTitle:(NSString *)title msg:(NSString *)msg cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips actionCallback:(GNRAlertViewActionBlock)callback{
    return [[self alloc]initWithTitle:title msg:msg cancelBtnTip:cancelBtnTip otherBtnTips:otherBtnTips actionCallback:[callback copy]];
}

//带输入框的
+ (instancetype)alertWithTitle:(NSString *)title alertFieldStyle:(GNRAlertFieldStyle)alertFieldStyle cancelBtnTip:(NSString *)cancelBtnTip otherBtnTips:(NSArray *)otherBtnTips textFieldActionCallback:(GNRAlertViewTextFieldActionBlock)callback{
    return [[self alloc]initWithTitle:title alertFieldStyle:alertFieldStyle cancelBtnTip:cancelBtnTip otherBtnTips:otherBtnTips textFieldActionCallback:[callback copy]];
}

//带定时器的
+ (instancetype)alertWithTitle:(NSString *)title msg:(NSString *)msg cancelBtnTip:(NSString *)cancelBtnTip otherBtnTip:(NSString *)otherBtnTip actionCallback:(GNRAlertViewActionBlock)callback timeDoneCallback:(GNRTimeDoneBlock)timeDoneCallback{
    NSAssert(otherBtnTip, @"otherBtnTip can not be nil");
    GNRAlertView * alert = [[GNRAlertView alloc]initWithTitle:title msg:msg cancelBtnTip:cancelBtnTip otherBtnTips:@[otherBtnTip] actionCallback:[callback copy]];
    alert.timeDoneBlock = nil;
    alert.timeDoneBlock = [timeDoneCallback copy];
    alert.isTimerAlert = true;
    return alert;
}

//MARK: - Setup
- (void)setUp{
    //    _dismissOnTapEnable = YES;
    _otherBtnTintColor = GNROrangeColor;
    _hightTextColor = GNROrangeColor;
    _btnAlignment = GNRAlertBtnAlignmentHorizontal;//默认横向排列
    _upLimitMoney = [GNRAlertConfiguration kDefaultUpLimitMoney];//金额上限
    
    self.alertStyle = [GNRAlertManager manager].defaultStyle;
    self.otherBtns = [NSMutableArray array];
    self.msgLabelAlignment = NSTextAlignmentCenter;
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    self.alpha = 0;
    
    [self registerNotifications];
}

- (void)installUI{
    //window
    GNRAlertViewController * alertVC = [GNRAlertViewController new];
    self.alertController = alertVC;
    alertVC.statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    alertVC.statusBarStyle = [UIApplication sharedApplication].statusBarStyle;
    [alertVC.view addSubview:self];
    
    self.containerWindow.rootViewController = alertVC;
    
    //title
    self.titleLabel.text = _title;
    
    //msg
    self.msgLabel.text = _msg;
    
    //btns
    [self installButtons];
    
    //maskView
    [self insertSubview:self.maskView atIndex:0];
    if (_alertFieldStyle == GNRAlertFieldStyleNone) {
        self.maskView.enabled = _dismissOnTapEnable;
    }else{
        self.maskView.enabled = NO;
    }
}

- (void)configUI{
    [self updateIconView];
    [self updateTitleMsgHeaderView];
    [self updateContentView];
}

- (NSInteger)totalBtnCount{
    NSInteger totalBtnCount = self.otherBtnTips.count + (self.cancelBtnTip.length?1:0);
    return totalBtnCount;
}

- (NSMutableArray *)totalBtnTips{
    if (!_totalBtnTips) {
        _totalBtnTips = [[NSMutableArray alloc] initWithArray:self.otherBtnTips];
        if (_cancelBtnTip) {
            [_totalBtnTips addObject:_cancelBtnTip];
        }
    }
    //    NSMutableArray *totalBtnTips = [[NSMutableArray alloc] initWithArray:self.otherBtnTips];
    //    if (_cancelBtnTip) {
    //        [totalBtnTips addObject:_cancelBtnTip];
    //    }
    return _totalBtnTips;
}

- (BOOL)isVertical{
    BOOL vertical = NO;//是否纵向排列
    NSInteger totalBtnCount = [self totalBtnCount];
    if (totalBtnCount<=2) {
        if (_isTimerAlert) {
            vertical = NO;
            GNRAlertLog(@"定时功能不支持纵向排列！");
        }else{
            vertical = _btnAlignment==GNRAlertBtnAlignmentVertical;//如果小于=2判断是否纵向排列
        }
    }else{
        vertical = YES;
    }
    return vertical;
}

//创建按钮
- (void)installButtons{
    //btns
    GNRWEAK_SELF;
    [self clearBtns];
    
    _totalBtnCount = [self totalBtnCount];
    _isVertical = [self isVertical];//是否纵向排列
    
    if (!_isVertical) {//横向排列
        NSMutableArray *btnTips = [[NSMutableArray alloc] initWithArray:self.otherBtnTips];
        NSInteger cancelIndex = -100;
        if (_cancelBtnTip) {
            if (_cancelBtnAlignment == GNRAlertCancelBtnAlignmentLeft) {
                [btnTips insertObject:_cancelBtnTip atIndex:0];
                cancelIndex = 0;
            } else {
                [btnTips addObject:_cancelBtnTip];
                cancelIndex = btnTips.count-1;
            }
        }
        
        [btnTips enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton * btn = [wself newBtn];
            //TODO: - 有定时器时
            if (wself.isTimerAlert && idx==btnTips.count-1) {
                obj = [NSString stringWithFormat:@"%@ %lus",obj,(unsigned long)wself.countDownMaxTime];
                [wself startTimer];
            }
            [btn setTitle:obj forState:UIControlStateNormal];
            if (cancelIndex == -100) {//无取消按钮
                [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateNormal];
                [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateHighlighted];
                btn.tag = (idx+1);
            } else if (cancelIndex==0) {//取消按钮
                if (idx == cancelIndex) {
                    btn.tag = -1;
                    [btn setTitleColor:GNRGrayTextColor forState:UIControlStateNormal];
                    [btn setTitleColor:GNRGrayTextColor forState:UIControlStateHighlighted];
                } else{
                    btn.tag = idx;
                    [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateNormal];
                    [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateHighlighted];
                }
            } else if (cancelIndex==(btnTips.count-1)) {
                if (idx == cancelIndex) {
                    btn.tag = -1;
                    [btn setTitleColor:GNRGrayTextColor forState:UIControlStateNormal];
                    [btn setTitleColor:GNRGrayTextColor forState:UIControlStateHighlighted];
                } else{
                    btn.tag = idx+1;
                    [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateNormal];
                    [btn setTitleColor:wself.otherBtnTintColor forState:UIControlStateHighlighted];
                }
            }
            if (btn.tag == -1) {
                wself.cancelBtn = btn;
            }
            
            [wself.otherBtns addObject:btn];
            [wself.alertView addSubview:btn];
        }];
        if (cancelIndex == -100) {
            [_cancelBtn removeFromSuperview];
            _cancelBtn = nil;
        }
    }else{//纵向排列
        self.tableView.backgroundColor = [UIColor clearColor];
        self.tableView.scrollEnabled = self.totalBtnTips.count > 3;
    }
}



- (void)layoutBtns{
    GNRWEAK_SELF;
    if (!self.isVertical) {//横向排列
        
        NSInteger btnCount = [self.otherBtns count];//[self totalBtnCount];
        
        [self.otherBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect frame;
            frame.size.width = (wself.configuration.kAlertWidth - wself.configuration.kSpace * (btnCount - 1)) / btnCount;
            frame.size.height = wself.configuration.kBtnHeight;
            frame.origin.x = idx * (frame.size.width + wself.configuration.kSpace);
            frame.origin.y = wself.contentView.frame.origin.y + wself.contentView.frame.size.height + wself.configuration.kSpace;
            obj.frame = frame;
            if (idx == wself.otherBtns.count - 1) {
                //self
                CGRect alerframe = wself.alertView.frame;
                alerframe.size.width = wself.configuration.kAlertWidth;
                alerframe.size.height = obj.frame.origin.y + obj.frame.size.height;
                wself.alertView.frame = alerframe;
            }
        }];
        
    }else{//纵向排列
        CGRect tableFrame = self.tableView.frame;
        tableFrame.origin.y = _contentView.frame.origin.y + _contentView.frame.size.height + self.configuration.kSpace;
        tableFrame.size.height = self.totalBtnCount <= 3 ? (self.totalBtnCount*self.configuration.kBtnHeight):(3.5*self.configuration.kBtnHeight);//半遮半漏 你懂得...
        tableFrame.size.width = self.configuration.kAlertWidth;
        self.tableView.frame = tableFrame;
        CGRect alerframe = wself.alertView.frame;
        alerframe.size.width = self.configuration.kAlertWidth;
        alerframe.size.height = _tableView.frame.origin.y + _tableView.frame.size.height;
        self.alertView.frame = alerframe;
    }
}

- (void)updateIconView{
    if (self.alertStyle!=GNRAlertStyleNoHeader &&
        self.alertStyle!=GNRAlertStyleShare) {
        self.iconImgView.image = _iconImage?:[GNRAlertManager manager].defaultIconImage;
        self.iconImgView.hidden = NO;
    }else{
        self.iconImgView.hidden = YES;
    }
}

- (void)updateContentView{
    if (_alertFieldStyle == GNRAlertFieldStyleCustomView) {
        [self.contentView addSubview:self.customView];
    }
}

- (void)updateTitleMsgHeaderView{
    //title(处理添加富文本支持)
    self.titleLabel.text = _title;
    if (_title) {
        NSAttributedString * attTit = [NSString replaceBracketsFromString:_title textColor:_hightTextColor font:_titleLabel.font lineSpace:0];
        self.titleLabel.attributedText = attTit;
    } else {
        self.titleLabel.attributedText = nil;
    }
    
    //msg(处理添加富文本支持)设置后重新刷新布局
    self.msgLabel.text = _msg;
    if (_msg) {
        NSAttributedString * attMsg = [NSString replaceBracketsFromString:_msg textColor:_hightTextColor font:_msgLabel.font lineSpace:self.configuration.kLineSpace];
        
        self.msgLabel.attributedText = attMsg;
    }else{
        self.msgLabel.attributedText = nil;
    }
    self.msgLabel.textAlignment = self.msgLabelAlignment;
    
    if (self.alertStyle == GNRAlertStyleBig) {//contentView 透明 header延伸到按钮的top位置
        self.titleLabel.textColor = [UIColor whiteColor];
        self.msgLabel.textColor = [UIColor whiteColor];
        self.headerView.image = _headerBgImage?:[GNRAlertManager manager].defaultHeaderBgImage;
        self.contentView.backgroundColor = [UIColor clearColor];
    }
    else if (self.alertStyle == GNRAlertStyleDefault) {
        self.headerView.image = _headerBgImage?:[GNRAlertManager manager].defaultHeaderBgImage;
        self.contentView.backgroundColor = [UIColor whiteColor];
        self.titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    }
    else if (self.alertStyle == GNRAlertStyleNoHeader) {//noheader
        self.titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        self.msgLabel.textColor = [UIColor colorWithHexString:@"#333333"];
        self.headerView.image = nil;
        self.contentView.backgroundColor = [UIColor whiteColor];
    }else if (self.alertStyle == GNRAlertStyleShare) {
        self.headerView.image = _headerBgImage?:[GNRAlertManager manager].defaultHeaderBgImage;
        self.headerView.contentMode = UIViewContentModeCenter;
        self.titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        self.msgLabel.textColor = [UIColor colorWithHexString:@"#fe4806"];
        self.contentView.backgroundColor = [UIColor whiteColor];
    }else if (self.alertStyle == GNRAlertStyleMerchant) {
        self.headerView.image = _headerBgImage?:[GNRAlertManager manager].defaultHeaderBgImage;
        self.titleLabel.textColor = [UIColor colorWithHexString:@"#1a1a1a"];
        self.msgLabel.textColor = [UIColor colorWithHexString:@"#444444"];
        self.contentView.backgroundColor = [UIColor whiteColor];
    }else if (self.alertStyle == GNRAlertStyleDoneOrder){
        self.headerView.image = _headerBgImage?:[GNRAlertManager manager].defaultHeaderBgImage;
        self.contentView.backgroundColor = [UIColor whiteColor];
        self.titleLabel.textColor = [UIColor colorWithHexString:@"#ff0000"];
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
    }
    self.titleLabel.font = [UIFont boldSystemFontOfSize:self.configuration.kTitFontSize];
    self.msgLabel.font = [UIFont boldSystemFontOfSize:self.configuration.kMsgFontSize];
}

- (void)clearBtns{
    [_cancelBtn removeFromSuperview];
    _cancelBtn = nil;
    [_otherBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [_otherBtns removeAllObjects];
}

- (void)updateCancelBtnTip:(NSString *)cancelBtnTip{
    self.cancelBtnTip = cancelBtnTip;
}

- (void)updateOtherBtnTips:(NSArray *)otherBtnTips{
    _otherBtnTips = otherBtnTips.mutableCopy;
    [self installButtons];
    [self layoutBtns];
}

//MARK: - Layout
- (void)layoutAllSubviews{
    self.configuration.style= _alertStyle;
    //super view
    self.frame = GNR_SCREENBOUNDS;
    self.maskView.frame = GNR_SCREENBOUNDS;
    
    //header
    self.headerView.frame = CGRectMake(0, 0, self.configuration.kAlertWidth, self.configuration.kHeaderHeight);
    //icon
    [self layoutIconView];
    //title
    [self layoutTitleLabel];
    //content
    [self layoutContentView];
    //btns
    [self layoutBtns];
    //center
    self.alertView.center = self.maskView.center;
    GNRAlertLog(@"layoutAllSubviews");
}

- (void)layoutIconView{
    if (self.alertStyle!=GNRAlertStyleNoHeader &&
        self.alertStyle!=GNRAlertStyleShare) {
        CGPoint iconCenter = self.iconImgView.center;
        iconCenter.x = self.configuration.kAlertWidth/2.0;
        CGSize iconSize = self.iconImgView.image.size;
        iconSize.height = iconSize.height>self.headerView.bounds.size.height?self.headerView.bounds.size.height:iconSize.height;
        iconSize.width = self.iconImgView.image.size.width*iconSize.height/self.iconImgView.image.size.height;
        CGRect iconBounds = CGRectZero;
        iconBounds.size = iconSize;
        self.iconImgView.bounds = iconBounds;
        if (self.alertStyle == GNRAlertStyleMerchant) {
            iconCenter.y = self.configuration.kHeaderHeight/2.0 + 5.0;
        } else {
            iconCenter.y = self.configuration.kHeaderHeight/2.0;
        }
        self.iconImgView.center = iconCenter;
    }else{
        self.iconImgView.hidden = YES;
    }
}

- (CGRect)layoutTitleLabel{
    CGRect titFrame = self.titleLabel.bounds;
    CGSize titSize = [self txtSize:_titleLabel];
    titFrame.origin.x = self.configuration.kLeadPadding;
    if(_alertStyle == GNRAlertStyleBig){
        titFrame.origin.y += self.configuration.kUHeight;
    } else if(_alertStyle == GNRAlertStyleMerchant) {
        titFrame.origin.y += 0;
    } else {
        titFrame.origin.y = titSize.height<=0?0:self.configuration.kTopPadding;
    }
    titFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2 * self.configuration.kLeadPadding, titSize.height);
    self.titleLabel.frame = titFrame;
    return titFrame;
}

- (void)layoutContentView{
    CGRect msgCntFrame = self.msgLabel.bounds;
    msgCntFrame.origin.x = self.configuration.kLeadPadding;
    msgCntFrame.origin.y = [self calculateMsgLabelY];
    if (_alertFieldStyle>0) {//field
        msgCntFrame.origin.y += self.configuration.kPadding;
        msgCntFrame = [self layoutFieldView:msgCntFrame];
    } else if (_alertFieldStyle == GNRAlertFieldStyleCustomView) {
        msgCntFrame.origin.x = 0;
        msgCntFrame.size.width = self.configuration.kAlertWidth;
        msgCntFrame.size.height = self.customView.frame.size.height;
        self.customView.frame = msgCntFrame;
    } else if (!_alertFieldStyle&&_linkTip) {//link
        if (!_linkBtn) {
            _linkBtn = [self newLinkBtn];
            [_linkBtn setTintColor:self.alertStyle==GNRAlertStyleBig?[UIColor whiteColor]:[UIColor blueColor]];
            [self.contentView addSubview:_linkBtn];
        }
        msgCntFrame.origin.y = CGRectGetMaxY(self.titleLabel.frame);
        msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2*self.configuration.kPadding, self.configuration.kBtnHeight-self.configuration.kPadding);
        _linkBtn.frame = msgCntFrame;
    } else {//msg
        CGSize msgSize = [self txtSize:_msgLabel];
        if (_alertStyle == GNRAlertStyleDefault) {
            if (CGRectGetHeight(self.titleLabel.frame)<=0) {
                msgCntFrame.origin.y += self.configuration.kPadding;
            }
        }
        msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2*self.configuration.kLeadPadding, msgSize.height);
        _msgLabel.frame = msgCntFrame;
    }
    
    //contentView
    CGRect cntFrame = self.contentView.frame;
    cntFrame.origin.y = CGRectGetMaxY(self.headerView.frame);
    cntFrame.size.width = self.configuration.kAlertWidth;
    cntFrame.size.height = msgCntFrame.origin.y + msgCntFrame.size.height;
    if (_alertFieldStyle != GNRAlertFieldStyleCustomView) {
        cntFrame.size.height += self.configuration.kBotmPadding;
    }
    self.contentView.frame = cntFrame;
    
    //header
    if (_alertStyle == GNRAlertStyleBig) {
        self.headerView.frame = CGRectMake(0, 0, self.configuration.kAlertWidth, self.contentView.frame.origin.y + self.contentView.frame.size.height);
    }
}


- (CGRect)layoutFieldView:(CGRect)msgCntFrame{
    switch (_alertFieldStyle) {
        case GNRAlertFieldStyleTextInput://普通文本
        {
            UITextField * moneyField = nil;
            if (!self.textFields.count) {
                moneyField = [self newTextField];
                moneyField.keyboardType = self.keyboardType;
                moneyField.secureTextEntry = self.secureTextEntry;
                moneyField.placeholder = _placeHolder.length?_placeHolder:_titleLabel.text;
                [_textFields addObject:moneyField];
            } else {
                moneyField = _textFields.firstObject;
            }
            msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2* self.configuration.kLeadPadding, self.configuration.kBtnHeight);
            moneyField.frame = msgCntFrame;
        }
            break;
        case GNRAlertFieldStyleLongTextInput:
        {
            GNRTextView * textView = nil;
            if (!self.textFields.count) {
                textView = [self newTextView];
                textView.keyboardType = self.keyboardType;
                textView.placeholder = _placeHolder;
                [_textFields addObject:textView];
            } else {
                textView = _textFields.firstObject;
            }
            msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2*self.configuration.kLeadPadding, self.configuration.kBtnHeight*2);
            textView.frame = msgCntFrame;
        }
            break;
        case GNRAlertFieldStyleMoneyInput://输入金额
        {
            UITextField * moneyField = nil;
            if (!self.textFields.count) {
                moneyField = [self newTextField];
                moneyField.leftView = [self newMoneyIconView];
                moneyField.keyboardType = UIKeyboardTypeDecimalPad;
                moneyField.placeholder = [NSString stringWithFormat:@"1.00元~%.2f元",_upLimitMoney];
                [_textFields addObject:moneyField];
            } else {
                moneyField = _textFields.firstObject;
            }
            msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2* self.configuration.kLeadPadding, self.configuration.kBtnHeight);
            moneyField.frame = msgCntFrame;
        }
            break;
        case GNRAlertFieldStyleLoginInput://登录
        {
            UITextField * userField = nil;
            UITextField * pswField = nil;
            if (self.textFields.count<2) {
                //用户名
                userField = [self newTextField];
                userField.keyboardType = UIKeyboardTypeDefault;
                userField.placeholder = @"用户名";
                [userField becomeFirstResponder];
                [_textFields addObject:userField];
                //密码
                pswField = [self newTextField];
                pswField.keyboardType = UIKeyboardTypeASCIICapable;
                pswField.placeholder = @"密码";
                [_textFields addObject:pswField];
            } else {
                userField = _textFields.firstObject;
                pswField = _textFields.lastObject;
            }
            msgCntFrame.size = CGSizeMake(self.configuration.kAlertWidth - 2*self.configuration.kLeadPadding, self.configuration.kBtnHeight);
            userField.frame = msgCntFrame;
            pswField.frame = CGRectMake(userField.frame.origin.x, userField.frame.origin.y+userField.frame.size.height+self.configuration.kPadding, userField.frame.size.width, self.configuration.kBtnHeight);
            msgCntFrame.size.height += self.configuration.kPadding + self.configuration.kBtnHeight;
        }
            break;
        default:
            break;
    }
    return msgCntFrame;
}

- (CGFloat)calculateMsgLabelY{
    CGFloat padding = _msg.length?self.configuration.kTitMsgPadding:0;
    CGFloat msgY = 0;
    if (_titleLabel.frame.size.height) {
        msgY = CGRectGetMaxY(_titleLabel.frame) + padding;
    } else {
        msgY = _titleLabel.frame.origin.y;
    }
    return msgY;
}

//MARK: - Timer
- (void)startTimer{
    [_timer setFireDate:[NSDate distantPast]];
}

- (void)stopTimer{
    [_timer setFireDate:[NSDate distantFuture]];
}

#pragma mark - Update Btn Enable
- (void)updateBtnEnableState{
    switch (_alertFieldStyle) {
        case GNRAlertFieldStyleMoneyInput:
        {
            __block UITextField * textField = _textFields.firstObject;
            [_otherBtns enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                BOOL valid = [self rangeValidMoney:textField.text];
                obj.enabled = valid;
            }];
            if (_cancelBtn) {//取消按钮始终 true
                [_cancelBtn setEnabled:true];
            }
        }
            break;
        default://其他不做限制
            break;
    }
}

//金额范围
- (BOOL)rangeValidMoney:(NSString *)money{
    if (money.doubleValue >= [GNRAlertConfiguration kDownLimitMoney]
        && money.doubleValue <= _upLimitMoney) {
        return true;
    }
    return false;
}

- (void)registerNotifications{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    
    [notificationCenter addObserver:self
                           selector:@selector(handleDidChangeStatusBarOrientation)
                               name:UIApplicationDidChangeStatusBarOrientationNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWasShown_gnr:)
                               name:UIKeyboardWillShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWasShown_gnr:)
                               name:UIKeyboardDidShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillBeHidden_gnr:)
                               name:UIKeyboardWillHideNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillBeHidden_gnr:)
                               name:UIKeyboardDidHideNotification
                             object:nil];
}

- (void)removeNotifications{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [notificationCenter removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

#pragma mark -  Action
- (void)alertBtnAction:(UIButton *)sender{
    alertBtnActionDismissBlockEnable = YES;
    actionSenderTag = sender.tag;
    if (_alertFieldStyle == GNRAlertFieldStyleNone ||
        _alertFieldStyle == GNRAlertFieldStyleCustomView ||
        sender.tag == -1) {//消失
        [self dismiss];
    }else{
        [self dismissBlock];
    }
}

- (void)linkBtnAction:(UIButton *)sender{
    linkBtnActionDismissBlockEnable = YES;
    [self dismiss];
}

- (void)maskViewAction:(id)sender{
    alertBtnActionDismissBlockEnable = YES;
    actionSenderTag = -100;
    [self dismiss];
}

- (void)timerAction:(id)sender{
    
    UIButton * btn = self.otherBtns.lastObject;
    //定时器-1
    if (_countDownMaxTime) {
        
        [btn setTitle:[NSString stringWithFormat:@"%@ %lus",_otherBtnTips.lastObject,(unsigned long)_countDownMaxTime--] forState:UIControlStateNormal];
        
    }else{
        
        //停止定时器
        [self freeTimer];
        
        btn.enabled = false;
        
        [btn setTitle:_otherBtnTips.lastObject forState:UIControlStateNormal];
        
        if (_timeDoneBlock) {
            _timeDoneBlock(self);
        }
    }
}

#pragma mark - Show
- (void)show{
    if (_isShown) {
        return;
    }
    _isShown = YES;
    
    [self installUI];
    
    [self configUI];
    
    [self updateBtnEnableState];
    
    [self layoutAllSubviews];
    
    //增加到管理器中
    [[GNRAlertManager manager]addAlertView:self];
    
    //显示
    GNRWEAK_SELF;
    self.alertView.transform =  CGAffineTransformMakeScale([GNRAlertConfiguration kAlertInitScale], [GNRAlertConfiguration kAlertInitScale]);
    [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration animations:^{
        wself.alpha = 1;
        wself.alertView.transform =  CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        wself.userInteractionEnabled = true;
    }];
    
}

#pragma mark - Dismiss
- (void)dismiss{
    if (self.ALERT_TYPE) {
        return;
    }
    
    GNRWEAK_SELF;
    [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration animations:^{
        wself.alpha = 0;
        wself.alertView.transform =  CGAffineTransformMakeScale([GNRAlertConfiguration kAlertInitScale], [GNRAlertConfiguration kAlertInitScale]);
    } completion:^(BOOL finished) {
        if (wself.alertFieldStyle==GNRAlertFieldStyleNone||
            wself.alertFieldStyle==GNRAlertFieldStyleCustomView) {
            [wself dismissBlock];
        }
        [[NSNotificationCenter defaultCenter] removeObserver:wself];
        if (wself.timer) {
            [wself freeTimer];
        }
        [[GNRAlertManager manager]removeAlertView:wself];
        [wself removeFromSuperview];
        if (wself.containerWindow) {
            wself.containerWindow.hidden = YES;
            [wself.containerWindow removeFromSuperview];
            wself.containerWindow = nil;
        }
    }];
}

- (void)dismissBlock{
    GNRWEAK_SELF;
    if (alertBtnActionDismissBlockEnable) {
        if (_actionBlock) {
            _actionBlock(actionSenderTag);
        }
        else if (_fieldAlertBlock){
            NSMutableArray * titles = [NSMutableArray array];
            [_textFields enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                switch (wself.alertFieldStyle) {
                    case GNRAlertFieldStyleMoneyInput:
                    {
                        //保留两位
                        [titles addObject:[NSString stringWithFormat:@"%.2f",[[obj text] doubleValue]]];
                    }
                        break;
                        
                    default:
                    {
                        [titles addObject:[obj text]];
                    }
                        break;
                }
            }];
            _fieldAlertBlock(actionSenderTag, titles, wself);
        }
        alertBtnActionDismissBlockEnable = NO;
    }
    if (linkBtnActionDismissBlockEnable) {
        if (_linkActionBlock) {
            _linkActionBlock();
        }
        linkBtnActionDismissBlockEnable = NO;
    }
}

//隐藏该Alert
- (void)gnr_hidden:(BOOL)hidden{
    if (_containerWindow) {
        _containerWindow.hidden = hidden;
    }else{
        self.hidden = hidden;
    }
}

- (void)gnrNew_hidden:(BOOL)hidden
{
    if (_coverWindow) {
        _coverWindow.hidden = hidden;
    }else{
        self.hidden = hidden;
    }
}

#pragma mark - UITextField Delegate
- (void)textFieldDidChange:(UITextField *)textField{
    /**新增*/
    
    if ([textField isEqual:self.moneyTextFiled]) {
        self.placeLab.hidden = textField.text.length;
    }
    switch (_alertFieldStyle) {
        case GNRAlertFieldStyleMoneyInput:
        {
            if (![GNRAlertView validForMoneyStr:textField.text]) {
                textField.text = textField.text.length?tmpText:nil;
            }else{//判断金额范围
                BOOL valid = [self rangeValidMoney:textField.text];
                if (!valid) {
                    //textField.text = tmpText;
                    textField.text = [NSString stringWithFormat:@"%.2lf",_upLimitMoney];
                    
                    if (_inputUpLimitMoneyBlock) {
                        _inputUpLimitMoneyBlock();
                    }
                }
            }
            [self updateBtnEnableState];
        }
            break;
        default:
            break;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    GNRWEAK_SELF;
    [_textFields enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == wself.textFields.count -1) {
            [wself hideKeyboard];
        }else{
            [[wself.textFields objectAtIndex:idx+1] becomeFirstResponder];
        }
    }];
    return true;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    tmpText = textField.text;
    if (!textField.text.length) {
        self.placeLab.hidden = NO;
    }else{
        self.placeLab.hidden = YES;
    }
    
    return true;
}

//MARK: - TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.totalBtnTips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellID = @"cellID";
    UIButton * btn = nil;
    UITableViewCell * cell = nil;
    
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    btn = [self newBtn];
    btn.frame = CGRectMake(0, 0, self.configuration.kAlertWidth, self.configuration.kBtnHeight-0.8);
    [_otherBtns addObject:btn];
    [cell.contentView addSubview:btn];
    
    [btn setTitle:self.totalBtnTips[indexPath.row] forState:UIControlStateNormal];
    [btn setTitleColor:(_cancelBtnTip.length&&indexPath.row==(self.totalBtnTips.count-1))?GNRGrayTextColor:_otherBtnTintColor forState:UIControlStateNormal];
    [btn setTitleColor:(_cancelBtnTip.length&&indexPath.row==(self.totalBtnTips.count-1))?GNRGrayTextColor:_otherBtnTintColor forState:UIControlStateHighlighted];
    
    //检查如果是输入金额 按钮初始化状态为不可点击
    BOOL enable = true;
    if (_alertFieldStyle==GNRAlertFieldStyleMoneyInput) {
        //最后一个取消按钮可以点击
        enable = (_cancelBtnTip.length&&indexPath.row==(self.totalBtnTips.count-1));
    }
    btn.enabled = enable;
    btn.tag = (_cancelBtnTip.length&&indexPath.row==(self.totalBtnTips.count-1))?-1:(indexPath.row+1);
    if (btn.tag==-1) {
        _cancelBtn = btn;
    }
    return cell;
}

#pragma mark - Keyboard Notify
//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWasShown_gnr:(NSNotification*)aNotification{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.configuration.kGNRAlertKeyBHeight = kbSize.height;
    if (!self.ALERT_TYPE) {
        [self upAnimation];
    }
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden_gnr:(NSNotification*)aNotification{
    if (!self.ALERT_TYPE) {
        [self downAnimation];
    }
}

- (void)hideKeyboard{
    [_textFields enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj resignFirstResponder];
    }];
    if (!self.ALERT_TYPE) {
        [self downAnimation];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (!_otherBtns.count && !self.ALERT_TYPE) {
        //        [self dismiss];
    }
    //    if (!self.ALERT_TYPE) {
    //        [self hideKeyboard];
    //    }
}

- (void)handleDidChangeStatusBarOrientation {
    [self layoutAllSubviews];
}

//alert 弹起
- (void)upAnimation{
    CGRect frame = self.alertView.frame;
    
    if (frame.origin.y < self.configuration.kGNRAlertKeyBHeight) {
        GNRWEAK_SELF;
        CGFloat kUpY = GNR_SCREENHEIGHT - self.alertView.bounds.size.height - self.configuration.kGNRAlertKeyBHeight;
        frame.origin.y = kUpY;
        
        [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            wself.alertView.frame = frame;
        } completion:^(BOOL finished) {
            
        }];
    }
}

//alert 归位
- (void)downAnimation{
    //    CGRect frame = self.alertView.frame;
    //    frame.origin.y = (GNR_SCREENHEIGHT - self.alertView.bounds.size.height) / 2.f;
    //    GNRWEAK_SELF;
    //    [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
    //        wself.alertView.frame = frame;
    //    } completion:^(BOOL finished) {
    //
    //    }];
}

//计算文字高度
- (CGSize)txtSize:(UILabel *)label{
    if (label.text==nil||!label.text.length) {
        return CGSizeZero;
    }
    CGFloat lineSpace = label==_titleLabel?0:self.configuration.kLineSpace;
    CGSize size = [GNRAlertView boundingRectWithSize:CGSizeMake(self.configuration.kMaxWidth,self.configuration.kMaxHeight) font:label.font lineSpacing:lineSpace label:label];
    return size;
}

//MARK: - Private
//判断如果包含中文
+ (BOOL)containChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }
    }
    return NO;
}

//判断是否满足金额数值的要求 >= 0.f 保留两位
+(BOOL)validForMoneyStr:(NSString *)moneyStr{
    NSString *pattern = @"^(([0-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMoney = [pred evaluateWithObject:moneyStr];
    return isMoney;
}

//计算文字高度，可以处理计算带行间距的
+ (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont*)font  lineSpacing:(CGFloat)lineSpacing label:(UILabel *)label{
    NSString * str = label.text;
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    paragraphStyle.paragraphSpacing = lineSpacing * 1.2;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:size options:options context:nil];
    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        if ([GNRAlertView containChinese:str]) {
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    return rect.size;
}



//2018.5.3新增
#pragma mark -初始化方法
- (instancetype)initWithAlertActionType:(ACTION_TYPE)action_type
                                  title:(NSString *)title
                                    des:(NSString *)des
                                actions:(void(^)(NSInteger index,id content))actions
{
    if (self = [super init]) {
        [self uuAlert_initWithUIFromActionType:action_type title:title des:des actions:actions];
    }
    return self;
}


-(UIImageView *)waringImage
{
    if (!_waringImage) {
        _waringImage = [[UIImageView alloc]init];
    }
    return _waringImage;
}

-(UILabel *)titleLab
{
    if (!_titleLab) {
        _titleLab = [[UILabel alloc]init];
        [_titleLab setFont:[UIFont boldSystemFontOfSize:17.0]];
        [_titleLab setTextColor:[UIColor colorWithHexString:@"#1a1a1a"]];
        [_titleLab setTextAlignment:NSTextAlignmentCenter];
        [_titleLab setNumberOfLines:0];
    }
    return _titleLab;
}
-(UILabel *)desLab
{
    if (!_desLab) {
        _desLab = [[UILabel alloc]init];
        [_desLab setFont:[UIFont systemFontOfSize:14.0]];
        [_desLab setTextColor:[UIColor colorWithHexString:@"#1a1a1a"]];
        [_desLab setTextAlignment:NSTextAlignmentCenter];
        [_desLab setNumberOfLines:0];
    }
    return _desLab;
}

-(UIButton *)knowBtn
{
    if (!_knowBtn) {
        _knowBtn = [[UIButton alloc]init];
        _knowBtn.layer.cornerRadius = 4.0f;
        [_knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
        [_knowBtn addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        _knowBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    }
    return _knowBtn;
}
-(UIButton *)sureBtn
{
    if (!_sureBtn) {
        _sureBtn = [[UIButton alloc]init];
        _sureBtn.layer.cornerRadius = 4.0f;
        [_sureBtn addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        _sureBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    }
    return _sureBtn;
}


- (UIWindow *)coverWindow{
    if (!_coverWindow) {
        _coverWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _coverWindow.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.6];
        _coverWindow.windowLevel = UIWindowLevelAlert;
        _coverWindow.hidden = NO;
        [_coverWindow makeKeyAndVisible];
    }
    return _coverWindow;
}

- (UITextView *)quickPhrasesTF
{
    if (!_quickPhrasesTF) {
        _quickPhrasesTF = [[UITextView alloc]init];
        _quickPhrasesTF.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f];
        _quickPhrasesTF.font      = [UIFont systemFontOfSize:13.0];
        _quickPhrasesTF.delegate  = self;
    }
    return _quickPhrasesTF;
}

- (UITextField *)moneyTextFiled
{
    if (!_moneyTextFiled) {
        _moneyTextFiled = [[UITextField alloc]init];
        _moneyTextFiled.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f];
        _moneyTextFiled.font      = [UIFont systemFontOfSize:13.0];
        _moneyTextFiled.delegate  = self;
        _moneyTextFiled.keyboardType = UIKeyboardTypeNumberPad;
        _moneyTextFiled.textAlignment = NSTextAlignmentCenter;
        [_moneyTextFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventAllEditingEvents];
    }
    return _moneyTextFiled;
}

- (UILabel *)placeLab
{
    if (!_placeLab) {
        _placeLab = [[UILabel alloc]init];
        _placeLab.textColor = [UIColor colorWithHexString:@"#bbbbbb"];
        _placeLab.textAlignment = NSTextAlignmentCenter;
        _placeLab.font = [UIFont systemFontOfSize:13.0];
    }
    return _placeLab;
}

- (UITextView *)versionUpdateTV
{
    if (!_versionUpdateTV) {
        _versionUpdateTV = [[UITextView alloc]init];
        _versionUpdateTV.textColor = [UIColor colorWithHexString:@"#1a1a1a"];
        _versionUpdateTV.font = [UIFont systemFontOfSize:14.0];
        _versionUpdateTV.textContainer.lineFragmentPadding = 0;
        _versionUpdateTV.textContainerInset = UIEdgeInsetsZero;
        _versionUpdateTV.editable = NO;
        
    }
    return _versionUpdateTV;
}
- (UIButton *)dismissBtnClcik{
    if (!_dismissBtnClcik) {
        _dismissBtnClcik = [UIButton buttonWithType:UIButtonTypeSystem];
        _dismissBtnClcik.backgroundColor = [UIColor clearColor];
        _dismissBtnClcik.frame = self.bounds;
        [_dismissBtnClcik addTarget:self action:@selector(_dismissBtnClcikAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dismissBtnClcik;
}

- (void)_dismissBtnClcikAction:(UIButton *)sender
{
    [self dismissWindow];
}
- (void)uuAlert_initWithUIFromActionType:(ACTION_TYPE)action_type
                                   title:(NSString *)title
                                     des:(NSString *)des
                                 actions:(void(^)(NSInteger index,id content))actions

{
    self.backItemAction = actions;
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 5.0f;
    self.ALERT_TYPE = action_type;
    self.desStr     = des;
    [self initWithData];
    [self installUIWithTitle:title des:des type:action_type];
    [self.titleLab setText:title];
    [self.desLab setText:des];
    [self layoutIfNeeded];
}


//组装UI
- (void)installUIWithTitle:(NSString *)title des:(NSString *)des type:(ACTION_TYPE)action_type
{
    
    [self layOut_addSubViews];
    switch (action_type) {
            
            //单个按钮
        case ACTION_TYPE_SINGLE:
        {
            [self configWithActionNoInputType:action_type des:des title:title NoHeadImg:NO];
        }
            break;
            //多个按钮
        case ACTION_TYPE_MORE:
        {
            [self configWithActionNoInputType:action_type des:des title:title NoHeadImg:NO];
        }
            
            break;
            //textView类型
        case ACTION_TYPE_TEXT:
        {
            [self configWithActionHaveInputType:action_type des:des title:title];
        }
            break;
            
            //金额类型
        case ACTION_TYPE_MONEY:
        {
            [self configWithActionHaveInputType:action_type des:des title:title];
        }
            break;
        case ACTION_TYPE_UPDATAVERION:
        {
            [self configUpdataVersion:action_type des:des title:title];
        }
            break;
            
        case ACTION_TYPE_NOHEAD:
        {
            [self configWithActionNoInputType:action_type des:des title:title NoHeadImg:YES];
        }
            break;
        default:
            break;
            
    }
    //maskView
    [self insertSubview:self.dismissBtnClcik atIndex:0];
    self.maskView.enabled = _dismissOnTapEnable;
}

- (void)layOut_addSubViews
{
    [self addSubview:self.waringImage];
    [self addSubview:self.titleLab];
    [self addSubview:self.desLab];
    [self addSubview:self.placeLab];
    [self addSubview:self.quickPhrasesTF];
    [self addSubview:self.moneyTextFiled];
    [self addSubview:self.versionUpdateTV];
    [self addSubview:self.knowBtn];
    [self addSubview:self.sureBtn];
}

- (void)close
{
    GNRWEAK_SELF;
    [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration animations:^{
        wself.alpha = 0;
        wself.transform =  CGAffineTransformMakeScale([GNRAlertConfiguration kAlertInitScale], [GNRAlertConfiguration kAlertInitScale]);
    } completion:^(BOOL finished) {
        if (wself.coverWindow) {
            wself.coverWindow.hidden = YES;
            [wself.coverWindow removeFromSuperview];
        }
    }];
}

- (void)initWithData
{
    self.isShown = YES;
}

- (void)configUpdataVersion:(ACTION_TYPE)action_type des:(NSString *)des title:(NSString *)title
{
    self.titleLab.preferredMaxLayoutWidth = (GNR_SCREENWIDTH - 88);
    [self.titleLab setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(20);
        make.right.mas_equalTo(self).offset(-20);
        make.top.mas_equalTo(self).offset(22);
    }];
    
    
    [self.versionUpdateTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(28);
        make.right.mas_equalTo(self).offset(-28);
        make.top.mas_equalTo(self.titleLab.mas_bottom).offset(14);
        //        make.height.mas_equalTo(110);
    }];
    CGFloat  actionWidth = ([UIScreen mainScreen].bounds.size.width - 146)/2;
    [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
    [self.knowBtn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
    self.knowBtn.layer.borderColor = [UIColor colorWithHexString:@"#999999"].CGColor;
    self.knowBtn.layer.borderWidth = 0.5;
    [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(27);
        make.top.mas_equalTo(self.versionUpdateTV.mas_bottom).offset(10);
        make.width.mas_equalTo(actionWidth);
        make.height.mas_equalTo(40);
    }];
    self.knowBtn.tag = 0;
    [self.sureBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
    [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.knowBtn.mas_centerY);
        make.right.mas_equalTo(self).offset(-27);
        make.width.mas_equalTo(self.knowBtn.mas_width);
        make.height.mas_equalTo(self.knowBtn.mas_height);
    }];
    self.sureBtn.tag = 1;
}

- (void)configWithActionHaveInputType:(ACTION_TYPE)action_type des:(NSString *)des title:(NSString *)title
{
    self.titleLab.preferredMaxLayoutWidth = (GNR_SCREENWIDTH - 88);
    [self.titleLab setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(20);
        make.right.mas_equalTo(self).offset(-20);
        make.top.mas_equalTo(self).offset(21);
    }];
    [self.placeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(20);
        make.right.mas_equalTo(self).offset(-20);
        make.top.mas_equalTo(self.titleLab.mas_bottom).offset(20);
    }];
    
    if (action_type == ACTION_TYPE_MONEY) {
        self.moneyTextFiled.backgroundColor = [UIColor clearColor];
        [self.moneyTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.top.mas_equalTo(self.titleLab.mas_bottom).offset(19);
            make.width.mas_equalTo(@171);
            make.height.mas_equalTo(@25);
        }];
    }else if (action_type == ACTION_TYPE_TEXT){
        self.quickPhrasesTF.backgroundColor = [UIColor clearColor];
        [self.quickPhrasesTF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.top.mas_equalTo(self.titleLab.mas_bottom).offset(19);
            make.width.mas_equalTo(@171);
            make.height.mas_equalTo(@25);
        }];
        
    }
    
    UIView *lineView = [[UIView alloc] init];
    lineView.layer.backgroundColor = [[UIColor colorWithRed:89.0f/255.0f green:89.0f/255.0f blue:89.0f/255.0f alpha:1.0f] CGColor];
    lineView.alpha = 1;
    [self addSubview:lineView];
    if (action_type == ACTION_TYPE_MONEY) {
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.moneyTextFiled.mas_bottom).offset(0);
            make.centerX.mas_equalTo(self);
            make.width.mas_equalTo(@171);
            make.height.mas_equalTo(@.5);
        }];
    }else if (action_type == ACTION_TYPE_TEXT){
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.quickPhrasesTF.mas_bottom).offset(0);
            make.centerX.mas_equalTo(self);
            make.width.mas_equalTo(@171);
            make.height.mas_equalTo(@.5);
        }];
    }
    
    CGFloat  actionWidth = ([UIScreen mainScreen].bounds.size.width - 146)/2;
    [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
    [self.knowBtn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
    self.knowBtn.layer.borderColor = [UIColor colorWithHexString:@"#1a1a1a"].CGColor;
    self.knowBtn.layer.borderWidth = 0.5;
    [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(27);
        make.top.mas_equalTo(lineView.mas_bottom).offset(21);
        make.width.mas_equalTo(actionWidth);
        make.height.mas_equalTo(40);
    }];
    self.knowBtn.tag = 0;
    [self.sureBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
    [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.knowBtn.mas_centerY);
        make.right.mas_equalTo(self).offset(-27);
        make.width.mas_equalTo(self.knowBtn.mas_width);
        make.height.mas_equalTo(self.knowBtn.mas_height);
    }];
    self.sureBtn.tag = 1;
}

-(void)configWithActionNoInputType:(ACTION_TYPE)action_type des:(NSString *)des title:(NSString *)title NoHeadImg:(BOOL)noHead
{
    self.titleLab.preferredMaxLayoutWidth = (GNR_SCREENWIDTH - 88);
    [self.titleLab setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    if (noHead) {
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(20);
            make.right.mas_equalTo(self).offset(-20);
            make.top.mas_equalTo(self).offset(22);
        }];
    }else{
        [self.waringImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.top.mas_equalTo(self).offset(25);
            make.height.mas_equalTo(54);
            make.width.mas_equalTo(54);
        }];
        
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(20);
            make.right.mas_equalTo(self).offset(-20);
            make.top.mas_equalTo(self.waringImage.mas_bottom).offset(21);
        }];
    }
    
    if (!des.length) {
        if (action_type == ACTION_TYPE_MORE) {
            CGFloat  actionWidth = ([UIScreen mainScreen].bounds.size.width - 146)/2;
            [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
            [self.knowBtn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
            self.knowBtn.layer.borderColor = [UIColor colorWithHexString:@"#1a1a1a"].CGColor;
            self.knowBtn.layer.borderWidth = 0.5;
            [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).offset(27);
                make.top.mas_equalTo(self.titleLab.mas_bottom).offset(21);
                make.width.mas_equalTo(actionWidth);
                make.height.mas_equalTo(40);
            }];
            self.knowBtn.tag = 0;
            [self.sureBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
            [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(self.knowBtn.mas_centerY);
                make.right.mas_equalTo(self).offset(-27);
                make.width.mas_equalTo(self.knowBtn.mas_width);
                make.height.mas_equalTo(self.knowBtn.mas_height);
            }];
            self.sureBtn.tag = 1;
        }else{
            
            [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
            [self.knowBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.titleLab.mas_centerX);
                make.top.mas_equalTo(self.titleLab.mas_bottom).offset(25);
                make.height.mas_equalTo(40);
                make.left.mas_equalTo(self).offset(27);
                make.right.mas_equalTo(self).offset(-27);
            }];
        }
    }else{
        self.desLab.preferredMaxLayoutWidth = (GNR_SCREENWIDTH - 88);
        [self.desLab setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
        [self.desLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(20);
            make.right.mas_equalTo(self).offset(-20);
            make.top.mas_equalTo(self.titleLab.mas_bottom).offset(15);
        }];
        
        if (action_type == ACTION_TYPE_MORE) {
            CGFloat  actionWidth = ([UIScreen mainScreen].bounds.size.width - 146)/2;
            [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
            [self.knowBtn setTitleColor:[UIColor colorWithHexString:@"#1a1a1a"] forState:UIControlStateNormal];
            self.knowBtn.layer.borderColor = [UIColor colorWithHexString:@"#1a1a1a"].CGColor;
            self.knowBtn.layer.borderWidth = 0.5;
            [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).offset(27);
                make.top.mas_equalTo(self.desLab.mas_bottom).offset(21);
                make.width.mas_equalTo(actionWidth);
                make.height.mas_equalTo(40);
            }];
            self.knowBtn.tag = 0;
            [self.sureBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
            [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(self.knowBtn.mas_centerY);
                make.right.mas_equalTo(self).offset(-27);
                make.width.mas_equalTo(self.knowBtn.mas_width);
                make.height.mas_equalTo(self.knowBtn.mas_height);
            }];
            self.sureBtn.tag = 1;
        }else{
            [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
            [self.knowBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(self.desLab.mas_centerX);
                make.top.mas_equalTo(self.desLab.mas_bottom).offset(25);
                make.height.mas_equalTo(40);
                make.left.mas_equalTo(self).offset(27);
                make.right.mas_equalTo(self).offset(-27);
            }];
        }
    }
}



- (void)addGesturesWithDidDismiss
{
    if (self.dismissOnTapEnable) {
        UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissWindow)];
        [self.coverWindow addGestureRecognizer:ges];
    }
}

- (void)dismissWindow
{
    [self removeFromSuperview];
    if (self.coverWindow) {
        self.coverWindow.hidden = YES;
        [self.coverWindow removeFromSuperview];
        self.coverWindow = nil;
    }
    [GNRAlertManager manager].alerts = nil;
}


//显示新版UU弹窗
-(void)showUU_Alert
{
    if ([[GNRAlertManager manager].alerts containsObject:self]) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [self.coverWindow setHidden:NO];
    self.transform =  CGAffineTransformMakeScale([GNRAlertConfiguration kAlertInitScale], [GNRAlertConfiguration kAlertInitScale]);
    [UIView animateWithDuration:self.configuration.kGNRAlertAnimationDuration animations:^{
        weakSelf.alpha = 1;
        weakSelf.transform =  CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        weakSelf.userInteractionEnabled = true;
    }];
    UIButton *maskView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    maskView.backgroundColor = UIColor.clearColor;
    [maskView addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [self.coverWindow addSubview:maskView];
    maskView.enabled = _dismissOnTapEnable;
    [self.coverWindow addSubview:self];
    
    CGFloat  height = 0.0;
    if (self.ALERT_TYPE == ACTION_TYPE_MONEY || self.ALERT_TYPE == ACTION_TYPE_TEXT) {
        CGFloat textHeight = [self contentHeight:self.quickPhrasesTF];
        height = 158  + textHeight;
    }else if (self.ALERT_TYPE == ACTION_TYPE_UPDATAVERION ){
        height = 243;
    }else if (self.ALERT_TYPE == ACTION_TYPE_NOHEAD){
        if (!self.desStr.length) {
            height = 114 + self.titleLab.frame.size.height ;
        }else{
            height = 123 + self.titleLab.frame.size.height + self.desLab.frame.size.height;
        }
    }else{
        if (!self.desStr.length) {
            height = 188 + self.titleLab.frame.size.height ;
        }else{
            height = 197 + self.titleLab.frame.size.height + self.desLab.frame.size.height;
        }
    }
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.coverWindow);
        make.left.mas_equalTo(self.coverWindow).offset(34);
        make.right.mas_equalTo(self.coverWindow).offset(-(34));
        make.height.mas_equalTo(height);
    }];
    [[GNRAlertManager manager]addNewAlertView:self];
}

- (void)itemClick:(UIButton *)sender
{
    //强制
    NSString *content;
    if (_isMandatory) {
        //强制
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"ishow"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        if (self.coverWindow) {
            self.coverWindow.hidden = YES;
            [self.coverWindow removeFromSuperview];
            self.coverWindow = nil;
        }
        [GNRAlertManager manager].alerts = nil;
        if (self.ALERT_TYPE == ACTION_TYPE_MONEY) {
            content = self.moneyTextFiled.text;
        }else if (self.ALERT_TYPE == ACTION_TYPE_TEXT){
            content = self.quickPhrasesTF.text;
        }else{
            content = @"";
        }
    }
    if (self.backItemAction) {
        self.backItemAction(sender.tag,content?:@"");
    }
}


#pragma mark -overide set
-(void)setWarningImageStr:(NSString *)warningImageStr
{
    _warningImageStr = warningImageStr;
    [self.waringImage setImage:[UIImage imageNamed:warningImageStr]];
}

-(void)setActionTitleArr:(NSArray<NSString *> *)actionTitleArr
{
    _actionTitleArr = actionTitleArr;
    if (actionTitleArr.count == 1) {
        [self.knowBtn setTitle:[actionTitleArr firstObject] forState:UIControlStateNormal];
    }else if (actionTitleArr.count == 2){
        [self.knowBtn setTitle:[actionTitleArr firstObject] forState:UIControlStateNormal];
        [self.sureBtn setTitle:[actionTitleArr objectAtIndex:1] forState:UIControlStateNormal];
    }
    //版本更新
    if (self.ALERT_TYPE == ACTION_TYPE_UPDATAVERION) {
        if (actionTitleArr.count == 1) {
            [self.knowBtn setBackgroundColor:[UIColor colorWithHexString:@"#1a1a1a"]];
            [self.knowBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.knowBtn.layer.borderWidth = 0.5;
            [self.knowBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).offset(27);
                make.top.mas_equalTo(self.versionUpdateTV.mas_bottom).offset(10);
                make.right.mas_equalTo(self).offset(-27);
                make.height.mas_equalTo(40);
            }];
            [self.sureBtn removeFromSuperview];
            [self layoutIfNeeded];
            self.knowBtn.tag = 0;
        }
    }
}

- (void)setVersionWordStr:(NSString *)versionWordStr
{
    _versionWordStr = versionWordStr;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 1;// 字体的行间距
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:14.0],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    self.versionUpdateTV.attributedText = [[NSAttributedString alloc] initWithString:versionWordStr attributes:attributes];
    
    CGFloat height = [self heightForString:self.versionUpdateTV andWidth:[UIScreen mainScreen].bounds.size.width - 124];
    [self.versionUpdateTV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo( height + 8);
    }];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(142 + height);
    }];
    [self layoutIfNeeded];
}

- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}


-(void)setUserContent:(NSString *)userContent
{
    _userContent = userContent;
    [self.placeLab setHidden:YES];
    [self.quickPhrasesTF setText:userContent];
    CGFloat textHeight = [self contentHeight:self.quickPhrasesTF];
    [self.quickPhrasesTF mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(textHeight);
    }];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(166 + textHeight);
    }];
}
//更改标题颜色
- (void)setTitleTextColor:(NSString *)titleTextColor
{
    _titleTextColor = titleTextColor;
    [self.titleLab setTextColor:[UIColor colorWithHexString:titleTextColor]];
}
//更改内容颜色
- (void)setDesTextColor:(NSString *)DesTextColor{
    
    _DesTextColor = DesTextColor;
    [self.desLab setTextColor:[UIColor colorWithHexString:DesTextColor]];
}

-(void)setPlaceHolderContent:(NSString *)placeHolderContent
{
    _placeHolderContent = placeHolderContent;
    [self.placeLab setText:placeHolderContent];
}

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat maxLength = _MAX_NUMBER?:2;
    NSString *toBeString = textView.text;
    if (toBeString.length) {
        [self.placeLab setHidden:YES];
    }else{
        [self.placeLab setHidden:NO];
    }
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    if (!position || !selectedRange)
    {
        if (toBeString.length > maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1)
            {
                textView.text = [toBeString substringToIndex:maxLength];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    CGFloat textHeight = [self contentHeight:self.quickPhrasesTF];
    [self.quickPhrasesTF mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(textHeight);
    }];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(166 + textHeight);
    }];
}

-(CGFloat)contentHeight:(UITextView *)objectLab
{
    CGFloat height = [objectLab.text boundingRectWithSize:CGSizeMake(objectLab.frame.size.width , MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:objectLab.font} context:nil].size.height;
    return height;
}

@end
